#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>

#define RTSP_PORT 8554
#define RTP_PORT 12345

int main() {
    int rtsp_sock, rtp_sock;
    struct sockaddr_in rtsp_address, rtp_address;
    int addrlen = sizeof(rtsp_address);
    char buffer[1024] = {0};
    const char* describe_response = "RTSP/1.0 200 OK\r\nCSeq: 1\r\nContent-Type: application/sdp\r\nContent-Length: 0\r\n\r\n";

    // 创建RTSP套接字
    rtsp_sock = socket(AF_INET, SOCK_STREAM, 0);
    if (rtsp_sock == 0) {
        std::cerr << "无法创建RTSP套接字" << std::endl;
        return 1;
    }

    rtsp_address.sin_family = AF_INET;
    rtsp_address.sin_addr.s_addr = INADDR_ANY;
    rtsp_address.sin_port = htons(RTSP_PORT);

    // 绑定RTSP套接字
    if (bind(rtsp_sock, (struct sockaddr *)&rtsp_address, sizeof(rtsp_address)) < 0) {
        std::cerr << "绑定RTSP套接字失败" << std::endl;
        return 1;
    }

    // 监听RTSP套接字
    if (listen(rtsp_sock, 3) < 0) {
        std::cerr << "监听RTSP套接字失败" << std::endl;
        return 1;
    }

    // 接受RTSP连接
    int new_socket = accept(rtsp_sock, (struct sockaddr *)&rtsp_address, (socklen_t*)&addrlen);
    if (new_socket < 0) {
        std::cerr << "接受RTSP连接失败" << std::endl;
        return 1;
    }

    // 读取DESCRIBE请求
    read(new_socket, buffer, 1024);
    std::cout << "接收到DESCRIBE请求：" << std::endl;
    std::cout << buffer << std::endl;

    // 发送DESCRIBE响应
    send(new_socket, describe_response, strlen(describe_response), 0);
    std::cout << "发送DESCRIBE响应" << std::endl;

    // 创建RTP套接字
    rtp_sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (rtp_sock < 0) {
        std::cerr << "无法创建RTP套接字" << std::endl;
        return 1;
    }

    // 配置组播地址
    rtp_address.sin_family = AF_INET;
    rtp_address.sin_addr.s_addr = inet_addr("239.0.0.1");
    rtp_address.sin_port = htons(RTP_PORT);

    // 发送RTP数据
    while (true) {
        // 在这里生成或读取视频数据
        char rtp_data[1500] = "模拟RTP数据包";
        sendto(rtp_sock, rtp_data, strlen(rtp_data), 0, (struct sockaddr *)&rtp_address, sizeof(rtp_address));
        std::cout << "发送RTP数据包" << std::endl;
        sleep(1); // 模拟视频流
    }

    // 关闭套接字
    close(rtp_sock);
    close(new_socket);
    close(rtsp_sock);

    return 0;
}
